package com.linghang.wusthelpercompetition.utils;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class WordFilter implements Filter {

    // 敏感词汇列表，可以根据需求扩展
    private static final String[] SENSITIVE_WORDS = {"敏感词1", "敏感词2", "敏感词3"};

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 将ServletRequest转换为HttpServletRequest
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 获取用户输入的文本
        String userInput = httpRequest.getParameter("content");

        // 检查是否包含敏感词汇
        if (userInput != null) { // 添加空值检查
            for (String word : SENSITIVE_WORDS) {
                if (userInput.contains(word)) {
                    // 替换敏感词汇为*
                    userInput = userInput.replaceAll(word, "*");
                }
            }
        }

        // 将处理后的文本传递给下一个过滤器或Servlet
        chain.doFilter(new WordFilteredRequest(httpRequest, userInput), response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化操作，可留空
    }

    @Override
    public void destroy() {
        // 过滤器销毁操作，可留空
    }
}